import React from "react";
import { getCode, getPhone } from "../../../api/info";
import { Form, Input, Button, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { useCountDown, useFd } from "../../../hooks";
import { setInfo } from "../../../store/slice/userSlice";
import { useDispatch } from "react-redux";

function CodeLogin() {
  let [codeform] = Form.useForm();

  //导入dis
  let dis = useDispatch();

  //倒计时
  let { count, start, isDown } = useCountDown(60);
  let nav = useNavigate();
  //登录
  const onFinish = async (values) => {
    let { data: res } = await getPhone(values);
    console.log(values);
    nav("/");
    dis(setInfo(res));
    console.log(res);
    Toast.show({
      icon: "success",
      content: "登录成功！",
    });
  };
  //发送验证码
  const send = async () => {
    try {
      let result = await codeform.validateFields(["tel"]);
      let { data: res } = await getCode(result.tel);
      codeform.setFieldValue("telCode", res.telCode);
      start();
    } catch {
      console.log("报错了");
      Toast.show({
        content: "手机号格式错误",
      });
    }
  };
  //封装防抖函数 Fd()
  const fd = useFd();
  return (
    <div>
      <Form
        form={codeform}
        layout="horizontal"
        mode="card"
        // onFinish={onFinish}
        onFinish={fd(onFinish)}
        style={{ "--prefix-width": "70px" }}
        footer={
          <Button block type="submit" color="primary">
            登录
          </Button>
        }
      >
        <Form.Item
          label="手机号"
          name="tel"
          rules={[
            { required: true, message: "手机号不能为空" },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入11位的手机号",
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          label="验证码"
          name="telCode"
          rules={[{ required: true, message: "验证码不能为空" }]}
          extra={
            <div>
              <Button fill="none" block onClick={send} disabled={isDown}>
                {isDown ? `${count}s后重发` : "发送验证码"}
              </Button>
            </div>
          }
        >
          <Input placeholder="请输入验证码" clearable />
        </Form.Item>
      </Form>
    </div>
  );
}

export default CodeLogin;
